import { useMount, useUpdateEffect } from "ahooks";
import { Table } from "antd";
import { useState } from "react";
import { useHistory } from "react-router-dom";
import { usePostRequest } from "../../http";
import { getEntryInfoList } from "../../http/apis/intentional-api";
import { pathName } from "../../routes/path";
import { getPathWithParams, stopAndTips } from "../../utils";
import { initDealEntryParams, initSearchParams, SearchParamsProps } from "./generator";
import { getColumns } from "./table-colums";

interface EntryInfoListRequestParams {
    contractNo?: string
    custManagerId: string | undefined
    custName?: string
    custType?: string
    entryNo?: string
    entryStatus: string
    idNo?: string
    orderByType: string
    pageNum: number | undefined
    pageSize: number | undefined
}

interface EntryInfo {
    list: Array<any>
    pageNum: number
    pageSize: number
    total: number
    totalPage: number
}
interface Result {
    code: string
    content: EntryInfo
    msg: string
}

const calcSize = (): number => {
    return window.innerHeight - 72 - 46 - 10 - 24 - 10 - 75
}

const IntentionalTable = (props: SearchParamsProps) => {

    const [entryInfo, setEntryInfo] = useState<EntryInfo>() // 列表返回数据
    const [runParam, setRunParam] = useState<EntryInfoListRequestParams>(initSearchParams(props)) // 列表请求参数
    const history = useHistory()

    // 进件处理
    const dealEntry = (item: any) => {
        if (stopAndTips(!item.fundingParty, '资方路由中，请稍后再进行进件操作')) return
        const params = initDealEntryParams(item)
        history.push(getPathWithParams(pathName.ENTRYINPUT, params))
    }

    // 定义列表请求地址和成功回调
    const params = { url: getEntryInfoList, successAction: (data: Result) => setEntryInfo(data.content) }
    const { run, loading } = usePostRequest(params)

    // 列表分页配置
    const onChange = (page: number | undefined, pageSize: number | undefined) => setRunParam({ ...runParam, pageNum: page, pageSize: pageSize })
    const pagination = { current: entryInfo?.pageNum, pageSize: entryInfo?.pageSize, total: entryInfo?.total, onChange: onChange }

    useMount(() => run(runParam))
    useUpdateEffect(() => { setRunParam({ ...runParam, entryStatus: props.entryStatus }) }, [props])
    useUpdateEffect(() => { run(runParam) }, [props.entryStatus, runParam])

    return <>
        <Table
            rowKey={v => v.id}
            scroll={{ y: calcSize(), scrollToFirstRowOnChange: true }}
            pagination={pagination}
            size="small"
            loading={loading}
            columns={getColumns({ props, dealEntry }) as Array<any>}
            dataSource={entryInfo?.list} />
    </>
}

export default IntentionalTable